using System;
using System.Web;
using System.Drawing.Design;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Drawing;
using System.Collections;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.GZip;


namespace ACM.cmsarea08.Controls
{
	[ToolboxData("<{0}:Itan_TextEditor runat=server Text=''></{0}:Itan_TextEditor>")]
	public class Itan_TextEditor : TextBox
    {
    	
        private string _title;
        private string _tinyPath;
        private string _language;
        private string _cssPath;
        private string _imgPath;
        private string _tempPath;
        private string _filemanagerPath;
        private EditorMode _edMode;
        private EditorResizableMode _resMode;
		private bool _GZipCompression;
		private bool _en_img;
		private bool _en_link;
		
        
       [Bindable(true),
		 Browsable (true),
         Category("Appearance"),
         Description("Get/Set Editor Title"),
         DefaultValue("Itan TextEditor 0.1")]
		public string Title
        {
            get
            {
                return _title;
            }
            set
            {
                _title = value;
            }
        }

       [Bindable(true),
		 Browsable (true),
         Category("Appearance"),
         Description("Get/Set Tiny MCE framework Path"),
         DefaultValue("/tinymce")]
		public string TinyMCEPath
        {
            get
            {
                return _tinyPath;
            }
            set
            {
                _tinyPath = value;
            }
        }

        [Bindable(true),
		 Browsable (true),
         Category("Default"),
         Description("Get/Set Custom Style (css) Path (only in Complete mode)"),
         DefaultValue("")] 		
		public string EditCssPath
        {
            get
            {
                return _cssPath;
            }
            set
            {
                _cssPath = value;
            }
        }
        
		[Bindable(true),
		 Browsable (true),
         Category("Default"),
         Description("Get/Set Image Upload/Browse Path (only in Complete mode)"),
         DefaultValue("")] 		
		public string ImagePath
        {
            get
            {
                return _imgPath;
            }
            set
            {
                _imgPath = value;
            }
        }

		[Bindable(true),
		 Browsable (true),
         Category("Default"),
         Description("Get/Set Html Template path (only in Complete mode)"),
         DefaultValue("")] 		
		public string TemplatePath
        {
            get
            {
                return _tempPath;
            }
            set
            {
                _tempPath = value;
            }
        }

		[Bindable(true),
		 Browsable (true),
         Category("Default"),
         Description("Get/Set FileManager Path (only in Complete mode)"),
         DefaultValue("")] 		
		public string FileManagerPath
        {
            get
            {
                return _filemanagerPath;
            }
            set
            {
                _filemanagerPath = value;
            }
        }

        
       [Bindable(true),
		 Browsable (true),
         Category("Layout"),
         Description("Get/Set Complete or Simple, editing layouts"),
         DefaultValue("Complete")]
        public EditorMode EditingMode
        {
            get
            {
                return _edMode;
            }
            set
            {
                _edMode = value;
            }
        }

        [Bindable(true),
		 Browsable (true),
         Category("Layout"),
         Description("Get/Set Resizible TextArea, Vertical, Both, None"),
         DefaultValue("None")]
        public EditorResizableMode Resizable
        {
            get
            {
                return _resMode;
            }
            set
            {
                _resMode = value;
            }
        }

        [Bindable(true),
		 Browsable (true),
         Category("Default"),
         Description("Enable/Disable GZip Javascript compression"),
         DefaultValue("false")]        
        public bool GZipCompression
        {
            get
            {
                return _GZipCompression;
            }
            set
            {
                _GZipCompression = value;
            }
        }        

        [Bindable(true),
		 Browsable (true),
         Category("Layout"),
         Description("Get/Set Editing Interface Language"),
         DefaultValue("it")]         
        public string Language
        {
            get
            {
                return _language;
            }
            set
            {
                _language = value;
            }
        }
        
		[Bindable(true),
		 Browsable (true),
         Category("Appearance"),
         Description("Enable/Disable Image Button (only in Complete mode)"),
         DefaultValue("")]         
        public bool Enable_Image
        {
            get
            {
                return _en_img;
            }
            set
            {
                _en_img = value;
            }
        }        

		[Bindable(true),
		 Browsable (true),
         Category("Appearance"),
         Description("Enable/Disable Link Button (only in Complete mode)"),
         DefaultValue("")]         
        
        public bool Enable_Href
        {
            get
            {
                return _en_link;
            }
            set
            {
                _en_link = value;
            }
        }        
		//private readonly TextBoxMode TextMode;
        

        
        public Itan_TextEditor() : base()   {
        	//inizializzatore Classe
        	_title = "Itan TextBox";
        	_tinyPath = "/tinymce";
        	_language = "it";
        	_GZipCompression = false;
        	_en_img = false;
        	_en_link = false;
        	_cssPath = "";
        	_tempPath = "";
        	_imgPath ="";
        	_edMode = EditorMode.Complete;
        	_resMode = EditorResizableMode.None;
        	base.Text = "";
        	this.TextMode =  TextBoxMode.MultiLine;
        	
        	
        }
 			
		protected override void OnLoad(EventArgs e)
		{
				base.OnLoad(e);      
				//eventi in load
				this.TextMode =  TextBoxMode.MultiLine;
				if(this.Attributes["class"]==null)
					this.Attributes.Add("class",this.ClientID);
				else
					this.Attributes["class"] += " " + this.ClientID;
				TinyMce_Include();
				//se siamo su gzip cambia 
				if(GZipCompression) TinyMce_GzipInclude();
				//Passa allo script:
				//if(!Page.IsPostBack) {
					if(EditingMode == EditorMode.Complete)
						TinyMce_CompleteInit();
					else
						TinyMce_SimpleInit();
				//}
		}
		
		private void TinyMce_Include() {
			HtmlGenericControl finInc = (HtmlGenericControl)this.Page.Header.FindControl("Include_tinysrc");
			if(finInc==null) {
//				HttpContext.Current.Response.Write("TINY NON PRESENTE");
				HtmlGenericControl Include = new HtmlGenericControl("script");
				Include.ID= "Include_tinysrc";
				Include.Attributes.Add("type", "text/javascript");
				if(!GZipCompression) 
					Include.Attributes.Add("src", this.TinyMCEPath + "/jscripts/tiny_mce/tiny_mce.js");
				else
					Include.Attributes.Add("src", this.TinyMCEPath + "/jscripts/tiny_mce/tiny_mce_gzip.js");
				
				
				this.Page.Header.Controls.Add(Include);		
			} 
			//HttpContext.Current.Response.Write("<hr>" + this.ID + " --> " + Include.UniqueID + "<br/>");
		}
		private void TinyMce_GzipInclude() {
			HtmlGenericControl finInc = (HtmlGenericControl)this.Page.Header.FindControl("Include_tinygzsrc");
			if(finInc==null) {			
				HtmlGenericControl Includegz = new HtmlGenericControl("script");
				Includegz.ID= "Include_tinygzsrc";
				Includegz.Attributes.Add("type", "text/javascript");
				System.Text.StringBuilder sbgz = new System.Text.StringBuilder();
				sbgz.Append("tinyMCE_GZ.init({ \n");
			    sbgz.Append("	plugins : \"table,advhr," +
			          (Enable_Href?"advlink,":"link,") +
			          ((Enable_Image && ImagePath!="")?"advimageNet,":"") +
			          "emotions,iespell,insertdatetime,preview,zoom,searchreplace,contextmenu,paste,filemanager\",\n");
			    sbgz.Append("	language : \"" + Language +"\",\n");
			    sbgz.Append("	disk_cache : true,\n");
			    sbgz.Append("	debug : false\n");
			    sbgz.Append("	});\n");
			    Includegz.InnerHtml = sbgz.ToString();
				this.Page.Header.Controls.Add(Includegz);		
			}
		}
		private void TinyMce_CompleteInit() {
				bool append=false;
				HtmlGenericControl Include_Init = (HtmlGenericControl)this.Page.Header.FindControl("tinyload_cinit");
				
				if(Include_Init==null) {
					Include_Init = new HtmlGenericControl("script");
					Include_Init.ID="tinyload_cinit";
					Include_Init.Attributes.Add("type", "text/javascript");
					Include_Init.InnerHtml="";
					Include_Init.Controls.Clear();
				} else 
					append=true;
				System.Text.StringBuilder sb = new System.Text.StringBuilder();
				sb.Append("\n//<![CDATA[\n");
				sb.Append("tinyMCE.init({\n");
				sb.Append("	mode : \"textareas\",\n");
				sb.Append("	editor_selector : \""+this.ClientID+"\",\n");
				//sb.Append("	elements : \"" + this.ClientID + "\",\n");
				sb.Append("	language : \"" + Language +"\",\n");
				sb.Append("	doctype : \"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Transitional//EN\\\" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\\\">\",\n");
				sb.Append("	plugins : \"table,advhr," +
				          (Enable_Href?"advlink,":"link,") +
				          ((Enable_Image && ImagePath!="")?"advimageNet,":"") +
				          "emotions,iespell,insertdatetime,preview,zoom,searchreplace,contextmenu,paste,filemanager\",\n");
				sb.Append("	theme_advanced_buttons1 : \"code,preview,zoom,search,replace,separator,undo,redo,cleanup,removeformat ,separator,cut,copy,paste,pasteword, separator,insertdate,inserttime,charmap,sub,sup,separator,bullist ,numlist,outdent,indent\",\n");
				sb.Append("	theme_advanced_buttons2: \"tablecontrols,separator ,image,hr,anchor,link,unlink,separator,forecolor,backcolor,styleselect");
				if(TemplatePath.Trim().Length>0)
					sb.Append(",template");
				sb.Append("\",\n");
				sb.Append("	theme_advanced_buttons3 : \"insertfile,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,formatselect,fontselect,fontsizeselect\",\n");
				sb.Append("	theme_advanced_toolbar_location : \"top\",\n");
				sb.Append("	theme_advanced_toolbar_align : \"left\",	\n");
				sb.Append("	theme_advanced_path : \"false\",\n");
				sb.Append(" theme_advanced_statusbar_location : \"bottom\",\n");
				sb.Append("	theme_advanced_disable : \"help\",\n");
				switch (Resizable) {
					case EditorResizableMode.Both:
						sb.Append("	theme_advanced_resizing : true,\n");break;
					case EditorResizableMode.Vertical:
						sb.Append("	theme_advanced_resizing : true,\n");
						sb.Append("	theme_advanced_resize_horizontal : false,\n");
						break;
				}
				sb.Append("	plugin_insertdate_dateFormat : \"%d-%m-%Y\",\n");
				sb.Append("	plugin_insertdate_timeFormat : \"%H:%M:%S\",\n");
				sb.Append(" extended_valid_elements : \"a[class|name|href|target|title|onclick|rel],img[style|class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],script[type|src]\" ");
				if(EditCssPath.Trim()!="")
					sb.Append(",\n	content_css : \"" +EditCssPath +"\"");
				if( (Enable_Image && ImagePath!="") )
					sb.Append(",\n	image_path : \"" + ImagePath +"\"\n");
				sb.Append("\n});\n");
				sb.Append("//]]>\n");
				if(!append) {
					
					Include_Init.InnerHtml = sb.ToString();
					this.Page.Header.Controls.Add(Include_Init);
					
				} else {
					if(Include_Init.InnerHtml.IndexOf(this.ClientID)==-1) {
						Include_Init.InnerHtml +="\n\n" + sb.ToString();
					}
				}
				
		}
		private void TinyMce_SimpleInit() {
				bool append=false;
				HtmlGenericControl Include_Init = (HtmlGenericControl)this.Page.Header.FindControl("tinyload_sinit");
				
				if(Include_Init==null) {
					Include_Init = new HtmlGenericControl("script");
					Include_Init.ID="tinyload_sinit";
					Include_Init.Attributes.Add("type", "text/javascript");
				} else 
					append=true;			
				System.Text.StringBuilder sb = new System.Text.StringBuilder();
				sb.Append("\n//<![CDATA[\n");
				sb.Append("tinyMCE.init({ \n");
				sb.Append("	mode : \"textareas\",\n");
				sb.Append("	editor_selector : \""+this.ClientID+"\",\n");
				//sb.Append("	elements : \"" + this.ClientID + "\",\n");
				sb.Append("	language : \"" + Language +"\",\n");
				sb.Append("	theme : \"advanced\",\n");
				sb.Append("	theme_advanced_buttons1 : \"bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink\",\n");
				sb.Append("	theme_advanced_buttons2 : \"\",\n");
				sb.Append("	theme_advanced_buttons3 : \"\",\n");
				sb.Append("	theme_advanced_toolbar_location : \"top\",\n");
				sb.Append("	theme_advanced_toolbar_align : \"left\",\n");
				sb.Append("	theme_advanced_statusbar_location : \"bottom\",\n");
				sb.Append("	extended_valid_elements : \"a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]\"\n");
				sb.Append("}); \n");
				sb.Append("//]]>\n");
				if(!append) {
					Include_Init.InnerHtml = sb.ToString();
					this.Page.Header.Controls.Add(Include_Init);			
				} else
					Include_Init.InnerHtml +="\n\n"+ sb.ToString();
		}
		
		protected override void Render(HtmlTextWriter output)
			{
			System.Text.StringBuilder sb = new StringBuilder();
			// Cattura l'output del dgrid base 
			StringWriter writer = new StringWriter();
			HtmlTextWriter buffer = new HtmlTextWriter(writer);

			base.Render(buffer);
			//Apro il Controllo
			sb.Append("<div id=\"" +this.UniqueID + "_container\">");
			//Stampo il Titolo
			if(Title!="") 
				sb.Append("<h3>" + Title + "</h3>");
			//Stampo il TextBox Normale
			sb.Append( writer.ToString() );
			
			//Chiudo il Controllo
			sb.Append("</div>");
			
			output.Write(sb.ToString());
			return;
			}        
    }
    
	public enum EditorMode {
		Complete,
		Simple
	}
	public enum EditorResizableMode {
		Vertical,
		Both,
		None
	}
}
